<?php 
	if(file_exists('functions.php')) {
     	require_once 'functions.php';
   	}

	if(!isset($_SESSION['isLogged'])) {
		header('Location: index.php');
		exit;
	}
 ?>


<!DOCTYPE html>
<html>
<head>
	<title>Buy</title>
</head>
<body>	
	<?php 
		
   		if(isset($_GET['bought'])) {
   			$moneyQ = "SELECT money FROM user WHERE user_id=".$_SESSION['user_id'].";";
   			$result = mysqli_query($db, $moneyQ);
   			if ($row = $result->fetch_assoc()){
   				$money = $row['money'];
   				if($money < $_GET['price']) {
   					echo "<p> <a href=\"index.php\">Optimist!</a> </p>";
   				} else {
   					echo '<p> <a href="index.php"> You have enough money, but we don\'t like you! </a> </p>';
   				}
   			}
   		}

		if(isset($_POST['traktors'])) { 
			$to_buy_id = $_POST['traktors'];

			$priceQ = "SELECT SUM(price) as sum FROM traktor WHERE traktor_id IN (".implode(',', $to_buy_id).")";
			
			$result = mysqli_query($db, $priceQ);
						
			if ($sum = mysqli_fetch_assoc($result)) {
				echo '<p> Wanna pay us '.$sum['sum'].' USD? </p>';
				echo "<p> <a href=\"buy.php?bought=1&price=".$sum['sum']."\">Take my Money!</a> </p>";
				echo "<a href=\"index.php\">Hell no!</a>";
			} else {
				echo "<a href=\"index.php\">Sorry</a>";
			}
			
		} else {
			echo "<a href=\"index.php\">Choose again</a>";
		}

	?>
</body>
</html>

<!-- echo '<pre>'.print_r($result).'</pre>'; -->
